package cn.cl.gulimall.product.service.impl;

import cn.cl.gulimall.product.entity.AttrEntity;
import cn.cl.gulimall.product.service.AttrService;
import cn.cl.gulimall.product.vo.AttrGroupWithAttrsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.cl.common.utils.PageUtils;
import cn.cl.common.utils.Query;

import cn.cl.gulimall.product.dao.AttrGroupDao;
import cn.cl.gulimall.product.entity.AttrGroupEntity;
import cn.cl.gulimall.product.service.AttrGroupService;
import org.springframework.util.StringUtils;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<AttrGroupEntity> page = this.page(
				new Query<AttrGroupEntity>().getPage(params),
				new QueryWrapper<AttrGroupEntity>()
		);

		return new PageUtils(page);
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
		// 检索的时候的字段
		String key = (String) params.get("key");
		QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>();
		if (!StringUtils.isEmpty(key)) {
			wrapper.and((obj) -> {
				obj
						.eq("attr_group_id", key)
						.or()
						.like("attr_group_name", key);
			});
		}
		if (catelogId == 0) {
			IPage<AttrGroupEntity> page = this.page(
					new Query<AttrGroupEntity>().getPage(params),
					wrapper
			);
			return new PageUtils(page);
		} else {
			wrapper.eq("catelog_id", catelogId);
			IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params), wrapper);
			return new PageUtils(page);
		}
	}

	@Autowired
	AttrService attrService;

	/**
	 * 获取分类下所有的分组以及属性
	 *
	 * @param catelogId
	 */
	@Override
	public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrsByCatelogId(Long catelogId) {
		// 1、查询分组信息
		List<AttrGroupEntity> attrGroupEntities = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
		if (attrGroupEntities == null || attrGroupEntities.size() <= 0) {
			return null;
		}
		List<AttrGroupWithAttrsVo> attrGroupWithAttrsVos = attrGroupEntities.stream().map((group) -> {
			AttrGroupWithAttrsVo attrGroupWithAttrsVo = new AttrGroupWithAttrsVo();
			BeanUtils.copyProperties(group, attrGroupWithAttrsVo);
			// 2、查询所有属性
			List<AttrEntity> attrs = attrService.getRelationAttr(attrGroupWithAttrsVo.getAttrGroupId());
			attrGroupWithAttrsVo.setAttrs(attrs);
			return attrGroupWithAttrsVo;
		}).collect(Collectors.toList());
		return attrGroupWithAttrsVos;
	}
}